package com.tencent.cloud.iov.recycler.flow;

import com.tencent.cloud.iov.action.IActionListener;
import com.tencent.cloud.iov.recycler.R;
import com.tencent.cloud.iov.recycler.block.ErrorResultItem;
import com.tencent.cloud.iov.recycler.item.IBlockItem;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.rx.SimpleObserver;

import java.util.ArrayList;
import java.util.List;

/**
 * 列表数据观察者
 *
 * 负责根据数据驱动视图层的更新
 *
 * @author showxiao
 * @date 2018/4/18
 */

public class RecyclerObserver extends SimpleObserver<List<IBlockItem>> implements RecyclerContract {

    private IActionListener mActionListener;
    private List<IBlockItem> mLastItems;

    public RecyclerObserver(IActionListener actionListener) {
        mActionListener = actionListener;
    }

    @Override
    public void onNext(List<IBlockItem> items) {
        super.onNext(items);
        mLastItems = items;
        mActionListener.onAction(ACTION_UPDATE_LIST, items);
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        // TODO: 2018/4/25 @showxiao 异常处理
        if (mLastItems != null && !mLastItems.isEmpty()) {
            onNext(mLastItems);
        } else {
            onNext(new ArrayList<IBlockItem>() {{
                add(new ErrorResultItem(ResourcesUtils.getString(R.string.error)));
            }});
        }
    }

    @Override
    public void onComplete() {
        super.onComplete();
        mActionListener = null;
    }
}